package com.feiyuan.core.controller.admin;

import com.feiyuan.common.exception.BusinessException;
import com.feiyuan.common.result.R;
import com.feiyuan.common.result.ResponseEnum;
import com.feiyuan.common.utils.CommonUtils;
import com.feiyuan.common.utils.MD5Utils;
import com.feiyuan.common.utils.ObjectMapperUtils;
import com.feiyuan.core.pojo.entity.AdminUser;
import com.feiyuan.core.service.AdminRoleMenuService;
import com.feiyuan.core.service.AdminRoleService;
import com.feiyuan.core.service.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AdminLoginController
 * @Description 登录控制器
 * @Author Xupf xupengfei131276@126.com
 * @Date 2021/9/30 9:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin/core/login")
//@CrossOrigin
public class AdminLoginController {

    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AdminRoleService adminRoleService;
    @Autowired
    private AdminRoleMenuService adminRoleMenuService;

    @PostMapping("/login")
    public Object login(@RequestBody AdminUser user) throws JsonProcessingException {
        String userName = user.getUserName();
        String password = user.getPassword();
        // 1.检测用户名和密码不能为空
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            throw new BusinessException(ResponseEnum.ADMIN_LOGIN_IS_NOT_NULL);
        }

        // 2.通过用户名查询用户信息
        AdminUser adminUser = adminUserService.getOne(new QueryWrapper<AdminUser>().eq("user_name", userName));
        if (adminUser == null) {
            throw new BusinessException(ResponseEnum.ADMIN_USER_NAME_IS_NOT_EXIST);
        }

        // 3.检测密码是否输入正确
        if (!MD5Utils.getSaltverifyMd5AndSha(password, adminUser.getPassword())) {
            throw new BusinessException(ResponseEnum.ADMIN_USER_PASSWORD_ERROR);
        }

        // 4.生成一个token返回给前台
        String token = CommonUtils.getToken();

        // 5.根据生成的token将用户信息放入缓存中
        redisTemplate.opsForValue().set("ADMIN_USER_" + token, ObjectMapperUtils.toJsonStr(adminUser), 60 * 60 * 2, TimeUnit.SECONDS);
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        resultMap.put("code", 20000);
        resultMap.put("data", map);
        return resultMap;
    }

    @GetMapping("/info")
    public R info(@RequestParam String token) throws JsonProcessingException {
        System.out.println("token: " + token);
        // 1.根据token获取用户信息
        String str = redisTemplate.opsForValue().get("ADMIN_USER_" + token);
        if (StringUtils.isEmpty(str)) {
            return R.ok().data("code", 10010).data("message", "请重新登录");
        }
        AdminUser adminUser = ObjectMapperUtils.readValue(str, AdminUser.class);

        // 2.查询用户所对应的角色
        List<String> roles = adminRoleService.selectRoles(adminUser.getId());
        adminUser.setRoles(roles);

        // 3.查询用户所对应的权限
        List<String> perms = new ArrayList<>();
        if (roles.contains("SYSADMIN")) {
            perms.add("*");
            adminUser.setPerms(perms);
        } else {
            perms = adminRoleMenuService.selectUserMenus(adminUser.getId());
            adminUser.setPerms(perms);
        }

        // 4.更新用户缓存
        redisTemplate.opsForValue().set("ADMIN_USER_" + token, ObjectMapperUtils.toJsonStr(adminUser), 60 * 60 * 3, TimeUnit.SECONDS);
        return R.ok().data("roles", perms).data("name", adminUser.getUserName()).data("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }

    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        // 1.删除用户token缓存
        String token = request.getHeader("ADMIN_TOKEN");
        redisTemplate.delete("ADMIN_USER_" + token);
        return R.ok();
    }
}
